package com.lucy.rabc.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.DynaBean;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.rabc.entity.SysRole;
import com.lucy.rabc.entity.SysUser;
import com.lucy.rabc.params.UserCreateParams;
import com.lucy.rabc.params.UserQueryParams;
import com.lucy.rabc.params.UserUpdateParams;
import com.lucy.rabc.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author kindear
 * 用户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("system")
@Api(tags = "用户管理")
public class UserController {
    @Autowired
    SysUserService userService;

    /** 新建用户 **/
    @PostMapping("users")
    @ApiOperation(value = "用户新建",notes = "")
    public ResponseDTO<Object> userCreate(@RequestBody @Validated UserCreateParams params){
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(params,sysUser,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        // userName 不允许重复
        Optional<SysUser> userOp = userService.getByUserName(params.getUserName());
        if (userOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,"用户名重复");
        }
        // 设置状态为启用
        sysUser.setStatus(1);
        // 获取首字母
        String initial = PinyinUtil.getFirstLetter(sysUser.getNickName(),"").substring(0,1);
        sysUser.setInitial(initial);
        return ResponseDTO.succData(userService.saveOne(sysUser));
    }


    @DeleteMapping("users/{userId}")
    @ApiOperation(value = "用户删除",notes = "")
    public ResponseDTO<Object> UserDelete(@PathVariable("userId") Long userId){
        userService.deleteOne(userId);
        return ResponseDTO.succMsg("删除成功");
    }

    @PutMapping("users")
    @ApiOperation(value = "用户更新",notes = "")
    public ResponseDTO<Object> userUpdate(@RequestBody @Validated UserUpdateParams params){
        Optional<SysUser> userOp = userService.getOne(params.getId());
        if (!userOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND);
        }
        SysUser user = userOp.get();
        BeanUtil.copyProperties(params,user,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        return ResponseDTO.succData(userService.updateOne(user));
    }

    @GetMapping("users")
    @ApiOperation(value = "用户列表",notes = "")
    public ResponseDTO<Object> userListQuery(UserQueryParams params){
        Sort sort;
        if(params.getOrder().equalsIgnoreCase("DESC")){
            sort = Sort.by(Sort.Direction.DESC, params.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, params.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(params.getPageNum() - 1 , params.getPageSize(), sort);
        /*
        构建 Example
         */
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(params,sysUser,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<SysUser> example = Example.of(sysUser);
        return ResponseDTO.succData(userService.getAll(pageable,example));
    }

    @GetMapping("users/{id}")
    @ApiOperation(value = "用户查询",notes = "")
    public ResponseDTO<Object> userQuery(@PathVariable("id") Long id){
        Optional<SysUser> userOp = userService.getOne(id);
        return userOp.<ResponseDTO<Object>>map(ResponseDTO::succData).orElseGet(() -> ResponseDTO.wrap(HttpStatus.NOT_FOUND));
    }

    @GetMapping("userInfo")
    @ApiOperation(value = "用户信息",notes = "")
    public ResponseDTO<Object> userInfoQuery() throws JsonProcessingException {
        // 获取登录ID -- 只有登录态用户才可以调用
        Long loginId = StpUtil.getLoginIdAsLong();

        Optional<SysUser> userOp = userService.getOne(loginId);
        if (!userOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND);
        }
        SysUser user = userOp.get();
        Map<String, Object> map = BeanUtil.beanToMap(user);
        List<String> perms = new ArrayList<>();
        Set<SysRole> roles = user.getRoles();
        for (SysRole role:roles){
            perms.addAll(role.getPermission());
        }
        perms.add("*:*:*");
        map.put("permissions",perms);
        return ResponseDTO.succData(map);
    }


    @PutMapping("user/{userId}/password")
    @ApiOperation(value = "密码重置",notes = "")
    public ResponseDTO<Object> resetPwd(@PathVariable("userId") Long userId,@RequestParam("password") String password){
        Optional<SysUser> userOp = userService.getOne(userId);
        if (!userOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND);
        }
        SysUser user = userOp.get();
        user.setPassword(password);
        return ResponseDTO.succData(userService.updateOne(user));
    }
}
